﻿using Finbook.Mvc.Services;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Finbook.Mvc.Infrastructure
{
    public class ContrabandModelBinder
        : IModelBinder
    {
        private readonly IContrabandAppService _contrabandAppService;
        public ContrabandModelBinder(IContrabandAppService contrabandAppService)
        {
            _contrabandAppService = contrabandAppService;
        }
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }
            if (bindingContext.ModelType == typeof(string))
            {
                var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
                if (valueProviderResult != ValueProviderResult.None)
                {
                    var rt = valueProviderResult.FirstValue;
                    //rt = rt.Replace("a", "【你这个a违规了，替换你】").Replace("@", "【我们不许你输入@】");
                    rt = _contrabandAppService.ReplaceContraband(rt, "ad", "【你这个a违规了，替换你】");
                    rt = _contrabandAppService.ReplaceContraband(rt, "p@", "【我们不许你输入@】");
                    bindingContext.Result = ModelBindingResult.Success(rt);
                }
            }
            return Task.CompletedTask;
        }
    }
}
